package com.rjj.wlqq.pdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public abstract class BasePDF implements PDF{
    /*字体*/
    private static String FONT = "static/pdf/font/simhei.ttf";

    /**
     * 字体这里设置了默认的，如果使用其他字体需要倒入字体，然后通过这个方法设定字体
     * @param FONT
     */
    public static void setFont(String FONT) {
        BasePDF.FONT = FONT;
    }


    @Override
    public boolean writeToPDF(Map<String, Object> data, String htmlTmp, OutputStream out) {
        String content = templateToString(data, htmlTmp);
        return write(content,out);
    }

    /**
     * 准备生成pdf
     */
    private boolean write(String content, OutputStream out){
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = null;
        try {
            writer = PdfWriter.getInstance(document, out);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // step 3
        document.open();
        // step 4
        XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
        fontImp.register(FONT);
        try {
            XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                    new ByteArrayInputStream(content.getBytes()), null, StandardCharsets.UTF_8, fontImp);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        // step 5
        document.close();
        return true;
    }

    /**
     * 要输出的字符串模板
     */
    public abstract String templateToString(Map<String, Object> data, String htmlTmp);
}
